
/**
 * Project Name:cats-web
 * File Name:BaseController.java
 * Package Name:com.catsic.core.web.controller
 * Date:2014年3月1日上午10:43:52
 * Copyright (c) 2014, oa.catsic.com All Rights Reserved.
 */
 
package com.catsic.base.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.catsic.base.BaseInfo;
import com.catsic.base.exception.CatsicException;

/**
 * ClassName: BaseController
 * Description: Spring Mvc 控制器基类
 * date: 2014年3月1日 上午10:43:52
 * author: yangyd
 */
public class BaseController {
	
	public static Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	public static final String CONTENT = "content";
	
	public static final String RESULT = "result";
	
	public static final String RESULT_SUCCESS = "success";
	
	public static final String RESULT_FAIL = "fail";
   /**
	* HandlerCatsicException:处理所有业务异常
	* @author yangyd
	* @param catsicException
	*/
	@ExceptionHandler(CatsicException.class)
	@ResponseBody
    public Map<String, Object> HandlerException(CatsicException ex) { 
		logger.error(ex.getCode() + ":" + ex.getMessage());
		return buildFailResult(ex.getCode(), ex.getMessage());
	}
	
	/**
	 * HandlerException:处理所有第三方jar抛出的异常
	 * @author yangyd
	 * @param Exception
	 */
	@ExceptionHandler(Exception.class) 
	@ResponseBody
    public Map<String, Object> HandlerException(Exception ex) {  
		String code = "000000";
		ex.printStackTrace();
		logger.error(code + ":" + ex.getMessage());
		return buildFailResult(code, "系统错误,稍后再试");
	}
	
	/**
	 * buildFailResult:处理异常错误
	 * @author yangyd
	 * @param errorCode
	 * @param errorMessage
	 * @return
	 */
	protected Map<String, Object> buildFailResult(String errorCode, String errorMessage) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("result", RESULT_FAIL);
		result.put("errorCode", errorCode);
		result.put("errorMessage", errorMessage);
		return result;
	}
	
	/**
	 * getCurrentUser:获得当前session
	 * @author yangyd
	 * @return
	 */
	public static BaseInfo getCurrentUser() {
		return (BaseInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}
	
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
	    binder.setAutoGrowCollectionLimit(Integer.MAX_VALUE);  
	} 
}
